import type { TableColumn } from "@/components/DynamicTable/types";
import { h } from "vue";
import {
  StatusTag,
  ProgressBar,
  ActionButtons,
} from "@/components/DynamicTable/components";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  deleteTask,
  deleteRemoteTask,
  retest,
  retestRemote,
  startWorkOrder,
  startRemoteWorkOrder,
  stopWorkOrder,
  stopRemoteWorkOrder,
  task_search_remote,
  processTask,
  syncAllAssets,
  syncNetworkAssets,
} from "@/api/task";
import { router } from "@/router";

export const statusMap = {
  0: { text: "待执行", type: "info" },
  1: { text: "运行中", type: "warning" },
  3: { text: "已完成", type: "success" },
  4: { text: "已失败", type: "danger" },
  2: { text: "已暂停", type: "info" },
};

// 表格列配置工厂函数
export const createTableColumns = (refreshData?: () => void): TableColumn[] => [
  // {
  //   label: "序号",
  //   prop: "index",
  //   width: 60,
  //   align: "center"
  //   // render: (row, column, cellValue, index) => index + 1
  // },
  {
    label: "任务名称",
    prop: "name",
    minWidth: 200,
    slot: "taskName",
  },
  {
    label: "任务数量",
    prop: "taskNum",
    minWidth: 100,
    render: (row, column, cellValue, index) => {
      return h(
        "div",
        {
          style: {
            backgroundColor: "#f5f7fa",
            padding: "10px",
            borderRadius: "4px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          },
        },
        row.taskNum
      );
    },
    // slot: "target"
  },
  {
    label: "扫描类型",
    prop: "target",
    minWidth: 100,
    render: (row, column, cellValue, index) => {
      const templateName = row.name?.split("-")?.[1];
      return h("div", templateName || "-");
      // return h("div", row.target);
    },
  },
  {
    label: "任务进度",
    prop: "progress",
    width: 180,
    // 使用render函数渲染进度条组件
    render: (row, column, cellValue, index) => {
      const current = row.progress;
      const total = 100;

      return h(ProgressBar, {
        current,
        total,
      });
    },
  },
  {
    label: "状态",
    prop: "status",
    minWidth: 100,
    // 使用render函数渲染状态标签
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.status,
        statusMap,
        // round: true
      });
    },
  },
  {
    label: "创建时间",
    prop: "creatTime",
    minWidth: 150,
  },
  {
    label: "结束时间",
    prop: "endTime",
    minWidth: 150,
  },
  {
    label: "操作",
    prop: "operation",
    width: 340,
    fixed: "right",
    // 使用render函数渲染操作按钮
    render: (row, column, cellValue, index) => {
      const actions = [
        {
          type: "button",
          label: "结果",
          command: "result",
          buttonType: "primary",
          plain: true,
        },
        // 处理按钮
        {
          type: "button",
          label: "处理",
          command: "handle",
          buttonType: "primary",
          plain: true,
        },

        // 同步下拉选择框
        {
          type: "dropdown",
          label: "同步",
          buttonType: "primary",
          plain: true,
          items: [
            {
              label: "全量资产同步",
              command: "sync-all",
            },
            {
              label: "网管资产同步",
              command: "sync-network",
            },
          ],
        },
        {
          type: "dropdown",
          label: "更多",
          buttonType: "primary",
          plain: true,
          items: [
            {
              label: "查看",
              command: "view",
            },
            {
              label: "删除",
              command: "delete",
            },
            {
              label: "开始",
              command: "start",
              show: (row: any) => row.status === 1 || row.status === 2,
            },
            {
              label: "暂停",
              command: "pause",
              show: (row: any) => row.status === 1 || row.status === 2,
            },
            {
              label: "重新测试",
              command: "retest",
              // show: (row: any) => row.status === 1 || row.status === 2,
            },
          ],
        },
      ];

      return h(ActionButtons, {
        actions: actions as any[],
        row,
        onAction: (command: string, row: any) => {
          // 这里可以传递事件处理函数
          // console.log("操作:", command, row);
          handleTableAction(command, row, refreshData);
        },
      });
    },
  },
];

// 为了向后兼容，导出默认的表格列配置
export const tableColumns = createTableColumns();

// 通过任务名称查询43列表获取对应的ID
const getRemoteTaskIdByName = async (
  taskName: string
): Promise<string | null> => {
  try {
    const { data } = await task_search_remote({
      search: taskName,
      pageIndex: 1,
      pageSize: 1000,
    });

    if (data && data.list) {
      // 查找完全匹配的任务名称
      const matchedTask = data.list.find((item: any) => item.name === taskName);
      return matchedTask ? matchedTask.id : null;
    }
    return null;
  } catch (error) {
    console.error("查询43任务列表失败:", error);
    return null;
  }
};

// 导出一些工具函数，用于处理操作
export const handleTableAction = async (
  command: string,
  row: any,
  refreshCallback?: (type?: { type: string; row: any }) => void
) => {
  switch (command) {
    case "view":
      refreshCallback &&
        refreshCallback({
          type: "view",
          row,
        });
      break;
    case "start":
      try {
        // 通过任务名称查询43列表获取对应的ID
        const remoteTaskId = await getRemoteTaskIdByName(row.name);

        const promises = [startWorkOrder({ ids: [row.id] })];
        if (remoteTaskId) {
          promises.push(startRemoteWorkOrder({ ids: [remoteTaskId] }));
        }

        await Promise.all(promises);
        ElMessage.success("开始任务成功");
        refreshCallback && refreshCallback();
      } catch (error) {
        ElMessage.error("开始任务失败");
        console.error("开始任务失败:", error);
      }
      break;
    case "pause":
      try {
        // 通过任务名称查询43列表获取对应的ID
        const remoteTaskId = await getRemoteTaskIdByName(row.name);

        const promises = [stopWorkOrder({ ids: [row.id] })];
        if (remoteTaskId) {
          promises.push(stopRemoteWorkOrder({ ids: [remoteTaskId] }));
        }

        await Promise.all(promises);
        ElMessage.success("暂停任务成功");
        refreshCallback && refreshCallback();
      } catch (error) {
        ElMessage.error("暂停任务失败");
        console.error("暂停任务失败:", error);
      }
      break;
    case "delete":
      console.log("删除任务:", row);
      ElMessageBox.confirm("确定删除该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        console.log("删除任务:", row);
        try {
          // 通过任务名称查询43列表获取对应的ID
          const remoteTaskId = await getRemoteTaskIdByName(row.name);

          const promises = [deleteTask({ ids: [row.id], delA: true })];
          if (remoteTaskId) {
            promises.push(
              deleteRemoteTask({ ids: [remoteTaskId], delA: true })
            );
          }

          await Promise.all(promises);
          ElMessage.success("删除成功");
          refreshCallback && refreshCallback();
        } catch (error) {
          ElMessage.error("删除失败");
          console.error("删除任务失败:", error);
        }
      });
      break;
    case "retest":
      ElMessageBox.confirm("确定重新测试该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          // 通过任务名称查询43列表获取对应的ID
          const remoteTaskId = await getRemoteTaskIdByName(row.name);

          const promises = [retest({ id: row.id })];
          if (remoteTaskId) {
            promises.push(retestRemote({ id: remoteTaskId }));
          }

          await Promise.all(promises);
          ElMessage.success("重新测试成功");
          refreshCallback && refreshCallback();
        } catch (error) {
          ElMessage.error("重新测试失败");
          console.error("重新测试失败:", error);
        }
      });
      break;
    case "result":
      router.push(`/taskmg/assetinfo?task=${row.name}`);
      break;
    case "handle":
      ElMessageBox.confirm("确定处理该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          await processTask({ task: row.name });
          ElMessage.success("任务已提交处理，正在后台处理");
          refreshCallback && refreshCallback();
        } catch (error) {
          ElMessage.error("处理任务失败");
          console.error("处理任务失败:", error);
        }
      });
      break;
    case "sync-all":
      ElMessageBox.confirm("确定进行全量资产同步吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          await syncAllAssets({ task: row.name });
          ElMessage.success("全量资产同步任务已启动");
          refreshCallback && refreshCallback();
        } catch (error) {
          ElMessage.error("全量资产同步失败");
          console.error("全量资产同步失败:", error);
        }
      });
      break;
    case "sync-network":
      // 触发打开同步弹窗的回调
      refreshCallback &&
        refreshCallback({
          type: "sync-network",
          row,
        });
      break;
    default:
      console.log("未知操作:", command, row);
  }
};

export const templateMap = [
  {
    label: "网管扫描",
    value: "684db8adb02f85e29536d9e8",
  },
  {
    label: "互联网探测",
    value: "684db9a5b02f85e29536da04",
  },
  {
    label: "探测与漏扫",
    value: "684eac94b02f85e29536e070",
  },
  {
    label: "深度扫描",
    value: "684f1336b02f85e29536e1f9",
  },
];

export const templateRemoteMap = [
  {
    label: "网管扫描",
    value: "684db8adb02f85e29536d9e8",
  },
  {
    label: "互联网探测",
    value: "684b2b500233b61964385f51",
  },
  {
    label: "探测与漏扫",
    value: "684eac94b02f85e29536e070",
  },
  {
    label: "深度扫描",
    value: "684f1336b02f85e29536e1f9",
  },
];
